package com.github.xzb617.client.flow.vm;

import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;

/**
 * 系统的相关指标
 * <p>
 *     1.CPU 负载
 *     2.MEMORY 占用率
 * </p>
 * @author xzb617
 */
public class MxInfo {

    private final OperatingSystemMXBean osMxBean;

    private static MxInfo mxInfo;
    private final static Object LOCK = new Object();

    /**
     * 单例获取 MxInfo
     * @return MxInfo
     */
    public static MxInfo getMxInfo() {
        if (mxInfo == null) {
            synchronized (LOCK) {
                if (mxInfo == null) {
                    mxInfo = new MxInfo();
                }
            }
        }
        return mxInfo;
    }

    private MxInfo() {
        // 初始化各类MxBean
        this.osMxBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
    }

    /**
     * 获取服务器cpu占用率
     * @return
     */
    public double cpuUsedRatio() {
        return (1.0 * this.osMxBean.getSystemCpuLoad() * 100);
    }

    /**
     * 获取服务器内存率
     * @return
     */
    public double memoryUsedRatio() {
        long totalPhysicalMemorySize = this.osMxBean.getTotalPhysicalMemorySize();
        long freePhysicalMemorySize = this.osMxBean.getFreePhysicalMemorySize();
        return 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize *100;
    }
}
